package com.test.web.config;

import com.he.core.ResultT;
import com.he.web.ex.NoAuthException;
import com.he.web.ex.OptionsException;
import com.he.web.filter.HttpParamsWrapper;
import com.he.web.util.Webs;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author heyanjing
 * date:2018-12-27 2018/12/27:18:06
 */
@Slf4j
@RestControllerAdvice
@AllArgsConstructor
public class ExceptionHanlder {

    private CustomConfig customConfig;


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultT argInvalid(HttpParamsWrapper request, MethodArgumentNotValidException ex) {
        String error = Webs.errorDetailMsgAll(request, ex);
        log.error("{}", error);
        if (customConfig.isDebug()) {
            String validateMsg = Webs.getValidateMsg(ex.getBindingResult());
            if (StringUtils.isNotBlank(validateMsg)) {
                return ResultT.errorWithArgs(validateMsg);
            }
        }
        return ResultT.error();
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResultT noRequestBody(HttpParamsWrapper request, HttpMessageNotReadableException ex) {
        if (request.isOption()) {
            if (customConfig.isDebug()) {
                log.info("{} {}", "options 请求", ex.getMessage());
            }
            return ResultT.success();
        }
        String error = Webs.errorDetailMsgAll(request, ex);
        log.error("{}", error);
        if (customConfig.isDebug()) {
            return ResultT.errorWithArgs("请求体数据不能为空");
        }
        return ResultT.error();

    }

    // @ExceptionHandler(HttpMessageNotReadableException.class)
    // public ResultT noRequestBody(HttpServletRequest request, HttpMessageNotReadableException ex) {
    //     if (customConfig.isDebug()) {
    //         return ResultT.errorWithArgs("请求体数据不能为空");
    //     }
    //     return ResultT.error();
    // }

    @ExceptionHandler(RuntimeException.class)
    public ResultT handleRuntimeException(HttpParamsWrapper request, RuntimeException ex) {
        String error = Webs.errorDetailMsgAll(request, ex);
        log.error("{}", error);
        return ResultT.error();
    }

    @ExceptionHandler(NoAuthException.class)
    public ResultT noAuth(NoAuthException e) {
        log.error("{}", "处理无授权异常");
        return ResultT.noAuth(e.getMessage());
    }

    @ExceptionHandler(OptionsException.class)
    public ResultT options(OptionsException e) {
        log.info("{}", "拦截器 拦截options");
        return ResultT.successWithMsg(e.getMessage());
    }

}
